//
//  WBNetworkManager+Extension.swift
//  TYCWeiBo
//
//  Created by 中发 on 2018/6/4.
//  Copyright © 2018年 中发. All rights reserved.
//

import Foundation

extension WBNetworkManager {
    
    /// 加载微博数据字典数组
    ///
    ///   - since_id:
    ///   - max_id: 
    /// - Parameter completion: 完成回调[list: 微博字典数组/是否成功]
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list: [[String: Any]]?, _ isSuccess: Bool) -> ()) {
        
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params = ["since_id": since_id,"max_id": max_id > 0 ? max_id - 1 : 0]
        
        tokenRequest(urlString: url, parameters: params) { (json, isSuccess) in
            //从json中获取statuses数据
            //如果as?失败，result = nil
            let result = (json as! NSDictionary)["statuses"] as? [[String: Any]]
            completion(result, isSuccess)
            
        }
    }
    
    /// 返回微博的未读数
    func unreadCount(compeletion: @escaping (_ count: Int) -> ()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid": uid]
        tokenRequest(urlString: urlString, parameters: params) { (json, isSuccess) in

            let dict = json as? [String: Any]
            let count = dict?["status"] as? Int
            compeletion(count ?? 0)
        }
        
    }
}

// MARK: - 发布微博
extension WBNetworkManager {
    
    /// 发布微博
    ///
    /// - Parameters:
    ///   - text: 要发布的文本
    ///   - image: 要上传的图像，为nil是，发布的是纯文本微博
    ///   - compeletion: 完成回调
    func postStatus(text: String, image: UIImage?, compeletion: @escaping (_ result: [String: Any]?, _ isSuccess: Bool) -> ()) -> () {
        /// 1.url
        let urlString: String
        //根据是否有图像，选择不同的接口地址
        if image == nil {
            urlString = "https://api.weibo.com/2/statuses/update.json"
        }else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        }
        
        /// 2.参数字典
        let parmas = ["status": text]
        //3.如果图像不为空，需要设置name 和 data
        var name: String?
        var data: Data?
        if image != nil {
            name = "pic"
            data = UIImagePNGRepresentation(image!)
        }
        /// 4.发起网络请求
        tokenRequest(wbHttpMethod: .POST, urlString: urlString, parameters: parmas, name: name, data: data) { (json, isSuccess) in
            compeletion(json as? [String: Any], isSuccess )
        }
    }
}

// MARK: - 用户信息
extension WBNetworkManager {
    
    //加载当前用户信息，用户登录成功后立即执行
    func loadUserInfo(compeletion: @escaping (_ dict: [String: Any]) -> ()) {
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid": uid]
        //发起网络请求
        tokenRequest(urlString: urlString, parameters: params) { (json, isSuccess) in
            //完成回调
            compeletion((json as? [String: Any]) ?? [:])
        }
        
    }
}

// MARK: - OAuth相关方法
extension WBNetworkManager {
    
    /// 加载accesstoken
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - compeletion: 完成回调【是否成功】
    func loadAccessToken(code: String, compeletion: @escaping (_ isSuccess: Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parmas = ["client_id": WBAppKey, "client_secret": WBAppSecret, "grant_type": "authorization_code", "code": code, "redirect_uri": WBRedirctURI]
        request(wbHttpMethod: .POST, urlString: urlString, parameters: parmas) { (json, isSuccess) in
            //直接用字典设置userAccount的属性
            
            self.userAccount.yy_modelSet(with: (json as? [String: Any]) ?? [:])
//            print(self.userAccount)
            //加载当前用户信息
            self.loadUserInfo(compeletion: { (dict) in
                //使用用户信息字典设置用户账户信息（昵称和头像地址）
                self.userAccount.yy_modelSet(with: dict)
                //保存模型
                self.userAccount.saveAccount()
                //完成回调
                compeletion(isSuccess)
            })
        }
    }
    
    
}
